package com.keson.guard.util;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
    private static final String NoPadding_CIPHER_ALGORITHM = "AES/ECB/NoPadding";//默认的加密算法
    private static final String NoPaddingpassword = "keson-123abcdefg";

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            byte[] byteContent = content.getBytes("UTF-8");

            SecretKeySpec securekey = new SecretKeySpec(NoPaddingpassword.getBytes(), "AES");//设置加密Key
            cipher.init(Cipher.ENCRYPT_MODE, securekey);//设置密钥和解密形式

            return new String(Base64.encode(cipher.doFinal(byteContent),Base64.NO_WRAP),"UTF-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @return
     */
    public static String decrypt(byte[] content) {
        try {
            content = Base64.decode(new String(content,"UTF-8"),Base64.NO_WRAP);

            Cipher cipher = Cipher.getInstance(NoPadding_CIPHER_ALGORITHM);
            SecretKeySpec securekey = new SecretKeySpec(NoPaddingpassword.getBytes(), "AES");//设置加密Key
            cipher.init(Cipher.DECRYPT_MODE, securekey);//设置密钥和解密形式

            return new String(cipher.doFinal(content), "UTF-8");
        } catch (Exception ex) {
            return null;
        }
    }
}
